﻿using System.Text.Json;
using System.Text.Json.Serialization;

namespace Digitalmes.Core.Common.Extensions;

public static class HttpResponseMessageExtensions
{
    public static readonly Lazy<JsonSerializerOptions> JsonSerializerWebOptions = new(() =>
    {
        JsonSerializerOptions options = new()
        {
            PropertyNameCaseInsensitive = true,
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            NumberHandling = JsonNumberHandling.AllowReadingFromString,
        };
        options.Converters.Add(new DateTimeOffsetConverterUsingDateTimeParse());
        options.Converters.Add(new DateTimesetConverterUsingDateTimeParse());
        return options;
    });

    /// <summary>
    /// 将HTTP响应消息反序列化为指定对象。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="message">HTTP响应消息</param>
    /// <returns></returns>
    public static async Task<T?> GetFromJsonAsync<T>(this HttpResponseMessage message)
        where T : class
    {
        var content = await message.Content.ReadAsStreamAsync();
        return await JsonSerializer.DeserializeAsync<T>(content, JsonSerializerWebOptions.Value); // 可尝试使用 JsonSerializerOptions.Web
    }

    // DateTimeOffset 转换器
    class DateTimeOffsetConverterUsingDateTimeParse : JsonConverter<DateTimeOffset>
    {
        public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            Debug.Assert(typeToConvert == typeof(DateTimeOffset));
            return DateTimeOffset.Parse(reader.GetString()!);
        }

        public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString());
        }
    }

    // DateTime 转换器
    class DateTimesetConverterUsingDateTimeParse : JsonConverter<DateTime>
    {
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            Debug.Assert(typeToConvert == typeof(DateTime));
            return DateTime.Parse(reader.GetString()!);
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString());
        }
    }
}
